﻿using Common;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CsvHelper;
using CsvHelper.Configuration;
using NewDevice.RS485;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Windows;
using WpfCommonCtlTest.Procdure;

namespace WpfCommonCtlTest.ViewModels

{
    public partial class Zh4006114N1ViewModel : ObservableObject
    {
        private Zh4006114N1 _zh4006114 = null!;
        private readonly List<DateEnrty> _dateEntity = new();

        private readonly CancellationTokenSource _cancellationToken = new();

        public Zh4006114N1ViewModel()
        {
            _allComs = new ObservableCollection<string>(SerialPort.GetPortNames());
        }

        [ObservableProperty]
        private string _chooseCom = "";

        [ObservableProperty]
        private int _choosebaudRate;

        [ObservableProperty]
        private ObservableCollection<string> _allComs;

        [ObservableProperty]
        private ObservableCollection<int> _allbaudRate = [115200, 96000];

        [RelayCommand]
        private void InitSys()
        {
            _zh4006114 = new Zh4006114N1(_chooseCom, _choosebaudRate);
        }

        [RelayCommand]
        private void Startup()
        {
            _zh4006114.MaxHistorySize = 600;
            _zh4006114.StartAsync();

            Task.Run(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Thread.Sleep(2000);
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Debug.WriteLine(_zh4006114.RegisterValues[0].Count);
                    });
                }
            });

            //Task.Factory.StartNew(UpdateDate, _cancellationToken.Token);
        }

        [RelayCommand]
        private void Close()
        {
            _cancellationToken.Cancel();
            _zh4006114.Disconnect();
        }

        private string _path = AppDomain.CurrentDomain.BaseDirectory + "CSV";

        [RelayCommand]
        private void Save()
        {
            string path = _path + "\\" + DateTime.Now.ToString("ddhhmmssfff") + ".csv";
            //File.Create(path);
            using (File.Create(path))
            {
                // 文件在此处被占用
            } //
            Thread.Sleep(1000);
            try
            {
                var historyDate1 = _zh4006114.GetRegisterHistory(1);
                var historyDate2 = _zh4006114.GetRegisterHistory(2);
                var historyDate3 = _zh4006114.GetRegisterHistory(3);
                var historyDate4 = _zh4006114.GetRegisterHistory(4);
                var historyDate5 = _zh4006114.GetRegisterHistory(5);
                var historyDate6 = _zh4006114.GetRegisterHistory(6);

                _zh4006114.ClearRegisterValues();
                if (historyDate1.Count == 0 || historyDate2.Count == 0 || historyDate3.Count == 0 || historyDate4.Count == 0 || historyDate5.Count == 0 || historyDate6.Count == 0)
                {
                    MessageBox.Show("寄存器数据为0！");
                    return;
                }
                for (int i = 0; i < historyDate1.Count; i++)
                {
                    DateEnrty entity = new DateEnrty();
                    entity.index1 = historyDate1[i];
                    entity.index2 = historyDate2[i];
                    entity.index3 = historyDate3[i];
                    entity.index4 = historyDate4[i];
                    entity.index5 = historyDate5[i];
                    entity.index6 = historyDate6[i];
                    _dateEntity.Add(entity);
                }

                var config = new CsvConfiguration(CultureInfo.InvariantCulture)
                {
                    HasHeaderRecord = false // 不写入表头
                };
                using var streamWriter = new StreamWriter(path, true, new UTF8Encoding(true));
                using var writer = new CsvWriter(streamWriter, config);
                var csvLength = new FileInfo(path).Length;
                if (csvLength == 0)
                {
                    //第一次写入
                    //注册映射
                    writer.Context.RegisterClassMap<DateEnrtyMap>();

                    ////写入表头
                    writer.WriteHeader<DateEnrty>();
                    writer.NextRecord(); // 结束表头行
                }

                writer.WriteRecords(_dateEntity);

                //writer.NextRecord();  //换行

                // 不需要手动Flush，using会自动处理
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                MyLog.Error(e);
            }

            MessageBox.Show("保存成功");
        }

        public void UpdateDate()
        {
            while (!_cancellationToken.IsCancellationRequested)
            {
                Thread.Sleep(10);
            }
        }
    }
}